import router from './router'
import store from './store'
import { Message } from 'element-ui'

const whiteList = ['/login'] // 无需令牌白名单

router.beforeEach(async (to, from, next) => {
  const hasToken = localStorage.getItem('token')

  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
    }

    const addRoutes = store.getters.addRoutes
    // console.log("addRoutes",addRoutes)
    if (addRoutes.length) {
      next()
    } else {
      try {
        const accessedRoutes = await store.dispatch('permission/generateRoutes')
        router.addRoutes(accessedRoutes)
        next({ ...to, replace: true })
      } catch (error) {
        await store.dispatch('user/resetToken')
        Message.error(error || 'Has Error')
        next(`/login?redirect=${to.path}`)
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
    }
  }
})
